#include "window5.h"
#include <QMessageBox>
#include <QPluginLoader>
#include <QSqlQuery>
#include <QVariant>
#include <QDebug>
Window5::Window5(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle("数据库操作");
    setGeometry(300, 200, 800, 600);
    show();

    //测试信号和槽
    connect(this, SIGNAL(sendSignal(int)), this, SLOT(getValue(int))); //连接信号和槽
    emit sendSignal(2);//发送信号

    init();
    //查询
    //select();

    //添加
    //insert();
}
Window5::~Window5(){
    if(db.isOpen()){
         db.close();
    }

}
/**
  失败处理：
 * 到 /home/denglibin/data2/program/Qt5.12.2/5.12.2/gcc_64/plugins/sqldrivers
 * 执行 ldd libqsqlmysql.so
 * 如果有 libmysqlclient.so.18 => not found
 * 安装 libmysqlclient.so.18
 * 下载地址：  https://launchpad.net/ubuntu/xenial/amd64/libmysqlclient18/5.6.25-0ubuntu1
 * 下载 libmysqlclient18_5.6.25-0ubuntu1_amd64.deb
 * 安装
 */
void Window5::init(){

   db = QSqlDatabase::addDatabase("QMYSQL");
   db.setHostName(hostname);
   db.setPort(port);
   db.setUserName(username);
   db.setDatabaseName(databaseName);
   db.setPassword(password);
   if (!db.open()) {
       QMessageBox::critical(this, QObject::tr("无法打开数据库"),
       "无法创建数据库连接！ ", QMessageBox::Cancel);
   }

}

//查询数据
void Window5::select(){
        QSqlQuery query(db);
        query.prepare("select id,name,amount from user where id=?");
        QVariant v(1);
        query.bindValue(0, v);
        if(query.exec()){//执行查询
            while(query.next()){
                int id = query.value("id").toInt();
                QString name  = query.value("name").toString();
                int amount = query.value("amount").toInt();
                qDebug() << id << " " << name << " " << amount << "\n";
            }
        }
        query.clear();
}


//添加
void Window5::insert(){
    //开启事务
    bool b = db.transaction();
    if(b){qDebug() << "开启事务成功" <<"\n";}
    QSqlQuery query(db);
    query.prepare("insert into student(id, name) values(?,?)");
    query.bindValue(0, QVariant(3));
    query.bindValue(1, QVariant("王五"));
    if(query.exec()){
        qDebug() << "插入成功" <<"\n";
    }
    //提交事务
    if(db.commit()){
        qDebug()<<"提交成功"<<"\n";
    }
    //回滚事物
//    if(db.rollback()){
//        qDebug() << "回滚成功";
//    }
    query.clear();
}

void Window5::getValue(int value){
    qDebug() << "接收到信号：" << value <<"\n";
}








